import CircleProgress from 'easy-circular-progress/src/index';
import UIcion from 'uview-ui/components/u-icon/u-icon.vue';
import UActionSheet from 'uview-ui/components/u-action-sheet/u-action-sheet.vue';
import UInput from 'uview-ui/components/u-input/u-input.vue';

import { queryBodyByProduce, queryHeaderByMenuId } from '@/api/formview';
import { Message } from '@/utils/utils';
import movableSwiper from '@/components/movable-swiper/movable-swiper.vue';

import { queryHeaderByTableId, getBodyData } from '@/api/formview';

// 页面头部详情的对应key
const HEADER_MAP = Object.freeze({
  DIVISION: 'DEPARTMENTNAME', // 职能部门（所在条线 ）
  ENTERPRISENAME: 'ENTERPRISENAME', // 乡镇名称
  PROGRAMNAME: 'PROGRAMNAME2', // 项目名称
  MONEY1: 'YSMX_YSJE', // 项目预算
  MONEY2: 'PAYMONEY', // 已经拨付
  MONEY3: 'WBF', // 未拨付
  RATEMONEY: 'RATE', // 资金使用率
  XMLX: 'XMLX', // 项目类型
  ENTERPRISECODE: 'PID' // 乡镇编码
});

// 钱的单位
const MONEY_UNIT = '元';

/**
 *
 *
 * @param {*} str string  // key,value,key1,value1
 * @return {key: value, key1: value1} | null
 */
export const getPropertyOfQuery = function(str) {
  let result = null;

  if (str && str.includes(',')) {
    const arr = str.split(',');
    result = Object.create(null);

    arr.map((e, i) => {
      if (i % 2 === 0) {
        result[e] = null;
      } else {
        for (const key in result) {
          if (result[key] === null) {
            result[key] = e;
            break;
          }
        }
      }
    });
  }
  return result;
};

// function ShowFileInfo(urls) {
//   return axios.get(url);
// }

// 环形进度条
const CircleProgressMy = {
  name: 'CircleProgressMy',

  components: {
    CircleProgress
  },

  props: {
    color: {
      type: String,
      default: '#FAAD14'
    },

    value: {
      type: Number,
      default: 0
    },

    title: {
      type: String,
      default: ''
    },

    circleTitle: {
      type: String,
      default: ''
    }
  },

  render() {
    const { default: defaultSlot } = this.$scopedSlots;

    return (
      <div class='myCircle-progress'>
        <CircleProgress
          strokeColor={this.color}
          strokeWidth={7}
          value={this.value}
          radius={30}
          transitionDuration={300}
          style={
            {
              stroke: 'red'
            }
          }
          scopedSlots={
            {
              footer: () => {
                return (
                  <div class='myCircle-progress-footer' >
                    {this.title}
                  </div>
                );
              }
            }
          }
        >
          <div
            class='myCircle-progress-content'
          >
            {
              defaultSlot &&
                defaultSlot(this.circleTitle) ||
                  this.circleTitle
            }
          </div>
        </CircleProgress>
      </div>

    );
  }
};

// 头部搜索区
const FormHead = {
  name: 'FormHead',

  components: {
    UIcion,
    UActionSheet,
    UInput
  },

  data() {
    return {
      actionShow: false,
      actionSelectValue: '齐贤街道(2021)',
      actionList: [
       
        {
          text: '齐贤街道(2021)',
          subText: '',
          color: ''
        }
      ]
    };
  },

  created() {
    this.changeActionListStatus();
  },

  methods: {
    inputConfirm(v) {
      console.log(v);
    },

    showAction() {
      this.actionShow = true;
    },

    actionClose() {
      this.actionShow = false;
    },

    changeActionListStatus() {
      const selectItem = this.actionList.find(item => item.text === this.actionSelectValue);
      this.actionList.forEach(item => {
        item.color = '#292A2D';
        item.subText = '';
      });

      selectItem.color = '#409EFF';
      selectItem.subText = '当前选中';
    },

    actionSelect(index) {
      const selectItem = this.actionList.find((item, i) => i === index);
      this.actionSelectValue = selectItem.text;
      this.changeActionListStatus();
      this.actionClose();
    }
  },

  render() {
    const actionSheet = () => {
      return (
        <UAction-Sheet
          value={ this.actionShow }
          list={ this.actionList }
          on={
            {
              close: () => this.actionClose(),
              click: (index) => this.actionSelect(index)
            }
          }
          mask-close-able={ false }
        />
      );
    };

    return (
      <div class='form-view-header'>
        <div class='form-view-header-select' >
          <span
            class='form-view-header-select-place'
            onclick={() => this.showAction()}
          >
            <U-Icion
              name='map-fill'
              color='#FFFFFF'
              size='38'
            />
            <span
              class='select-content'
              style={
                {
                  'margin-left': '5px'
                }
              }
            >
              {
                this.actionSelectValue
              }
            </span>
          </span>
          <span>
            <U-Icion
              name={!this.actionShow && 'arrow-down-fill' || 'arrow-up-fill'}
              style={
                {
                  'margin-left': '3px'
                }
              }
              color='#FFFFFF'
              size='18'
            />
          </span>
        </div>

        <div class='form-view-header-search-input'>
          {/* 搜索框 不要了 */}
          {/* <div>
            <U-Icion
              name='search'
              color='#FFFFFF'
              size='30'
              style={
                {
                  'margin-right': '5px',
                  'margin-left': '5px'
                }
              }
            />

            <U-Input
              placeholder='搜索'
              on={
                {
                  confirm: v => this.inputConfirm(v)
                }
              }
            />
          </div> */}

        </div>
        {
          actionSheet()
        }
      </div>
    );
  }
};

// 项目详情
const FormDetail = {
  name: 'FormDetail',

  components: {
    CircleProgressMy
  },

  props: {
    item: {
      type: Object,
      default: () => ({
        title: '齐贤街道无障碍社区建设（迎驾桥社区）工程项目',
        status: '建设中',
        enterprise: '城建办',
        money: '70.99万元',
        pmoney: '56.79万元',
        bmoney: '14.2万元',
        memo: '齐贤街道齐贤街道无障碍社区建设（迎驾桥社区）工程项目无障碍社区建设（迎驾桥社区）工程项目'
      })
    }
  },

  render() {
    const { item } = this;
    return (
      <div
        class='FormDetail'
      >
        <div
          class='FormDetail-container'
        >

          { /* 项目名称 */ }
          <div
            class='FormDetail-row'
            style={
              {
                '--row-Num': 1
              }
            }
          >
            <div class='FormDetail-row-item'>
              <label class='row-title'>
                项目名称:
              </label>
              <div>
                { item[HEADER_MAP.PROGRAMNAME] }
              </div>
            </div>
          </div>

          <div
            class='FormDetail-row'
            style={
              {
                '--row-Num': 2,
                '--ellipsis-Num': 1
              }
            }
          >
            <div class='FormDetail-row-item ' >
              <label class='row-title'>
                项目状态:
              </label>
              <div
                class='ellipsis'
              >
                建设中
              </div>
            </div>
            <div class='FormDetail-row-item '>
              <label class='row-title'>
                职能部门:
              </label>
              <span
                class='ellipsis'
              >
                { item[HEADER_MAP.DIVISION] }
              </span>
            </div>
          </div>

          <div
            class='FormDetail-row'
            style={
              {
                '--row-Num': 2,
                '--ellipsis-Num': 1
              }
            }
          >
            <div class='FormDetail-row-item ' >
              <label class='row-title'>
                项目预算:
              </label>
              <div
                class='ellipsis'>
                { item[HEADER_MAP.MONEY1] || 0 + MONEY_UNIT }
              </div>
            </div>
            <div class='FormDetail-row-item '>
              <label class='row-title'>
                已经拨付:
              </label>
              <div
                class='ellipsis' style='font-weight:bolder'>
                { item[HEADER_MAP.MONEY2] || 0 + MONEY_UNIT }
              </div>
            </div>
          </div>

          <div
            class='FormDetail-row'
            style={
              {
                '--row-Num': 2,
                '--ellipsis-Num': 1
              }
            }
          >
            <div class='FormDetail-row-item' >
              <label class='row-title'>
                尚未拨付:
              </label>
              <div
                class='ellipsis'>
                { item[HEADER_MAP.MONEY3] || 0 + MONEY_UNIT }
              </div>
            </div>
          </div>

          <div
            class='FormDetail-row'
            style={
              {
                '--row-Num': 2,
                '--ellipsis-Num': 3
              }
            }
          >
            <div class='FormDetail-row-item ellipsis' >
              <label class='row-title'>
                项目简述:
              </label>
              <span class='ellipsis' style='margin-top: 5px;' >
                { item[HEADER_MAP.PROGRAMNAME] }
              </span>

            </div>
          </div>

          <div
            class='FormDetail-row-item-circle'
          >
            <Circle-Progress-My
              color='#FAAD14'
              title='资金使用率'
              circleTitle={ item[HEADER_MAP.RATEMONEY] || 0 + '%' }
              value={ item[HEADER_MAP.RATEMONEY] || 0 }
              style={
                {
                  'margin-right': '5px'
                }
              }
            />

            <Circle-Progress-My
              color='#FAAD14'
              title='项目完成度'
              circleTitle='100%'
              value={100}
            />
          </div>

        </div>
      </div>
    );
  }
};

const FileNoItem = {
  name: 'FileNoItem',

  props: {
    title: {
      type: String,
      default: ''
    },

    content: {
      type: String,
      default: ''
    },

    fileNo: {
      type: Object,
      default: () => {}
    },

    linkPage: {
      type: String,
      default: ''
    },
    imgSrc: {
      type: String,
      default: '1111'
    }

  },

  methods: {
    fileNoClick() {
      const query = {
        tableId: this.fileNo.id,
        tableName: this.fileNo.tableName,
        programeCode: this.$route.query.filter.split(',')[1],
        tableType:this.fileNo.tableType
      };
      const param = {
        path: '/projectDetail',
        query
      };
      this.$router.push(param);
    }
  },

  render() {
    return (
      <div class='FileNoItem' onclick={ () => this.fileNoClick(this.fileNo) }>
        <span style='vertical-align: middle;margin-right:5px'>
          <img class='imgClass' style='width: 30px;' src={
            this.imgSrc
          } />

        </span>
        <span style='vertical-align: super;'>{ this.title }</span>
      </div>
    );
  }
};

export default {
  name: 'FormView',
  components:{
     movableSwiper
  },
  data() {
    return {
      fileNos: [],
      selImages: [],
      produceData: {},
      headerLoading: false,
      levelNum:this.$route.query.levelNum,
      movHeight:'calc(70vh)',
      dataList:[],
      header:[]
    };
  },

  created() {
    this.initData();
  },

  components: {
    FormDetail,
    FormHead,
    FileNoItem

  },

  methods: {
    initData() {
      const { collectData } = this;
      collectData();
    },

    getBodyByProduce(data) {
      this.headerLoading = true;
      data.pageIndex= 0
      data.pageSize= 10
      data.pageType= 1
      queryBodyByProduce(data).then(res => {
        this.headerLoading = false;
        if (res.success) {
          const { data } = res;
          if (data && data.length) {
            const ddata = data[0];
            const moneyRage = ddata[HEADER_MAP.RATEMONEY]; // '100.00%'

            ddata[HEADER_MAP.RATEMONEY] = Number(moneyRage &&
                moneyRage.replace(/\%$/, '') || 0);

            this.produceData = ddata;
          }
        } else {
          Message(res.message);
        }
      });
    },
    queryHeaderByMenuId(data) {
      this.headerLoading = true;
      queryHeaderByMenuId(data).then(res => {
        this.headerLoading = false;
        if (res.success) {
          const { data } = res;
          if (data) {
            this.fileNos = data.childrenTableInfos.filter(item =>item.display===1);
            const url = [
              require('@/static/img/formView/file.png'),
              require('@/static/img/formView/file1.png'),
              require('@/static/img/formView/file2.png'),
              require('@/static/img/formView/file3.png'),
              require('@/static/img/formView/file4.png')
            ];
            this.fileNos.map((item, index) => {
              if (index <= 4) {
                item.imgSrc = url[index];
              } else {
                item.imgSrc = url[index % 4];
              }
            });
            console.log(this.fileNos);
             this.getHeader()
          }
        } else {
          Message(res.message);
        }
      });
    },

    getHeader() {
        queryHeaderByTableId({
          tableId:this.fileNos[0].id
        }).then(res => {
          if (res.success) {
            // res.data.fliter(item => item.display===1)
            this.header = res.data.filter(item => item.display === 1);
            this.header.sort((a, b) => Number(a.orderId) - Number(b.orderId));
          } else {
            this.header = [];
          }
          this.getData();
        });
      },
      getData() {
        getBodyData({
          cprogramname: '',
          filterList: [{ col: 'PROGRAMCODE', value: this.$route.query.filter.split(',')[1], Symbol: 'eq' }],
          pageIndex: 0,
          pageSize: 10000,
          pageType: 1,
          tableId: this.fileNos[0].id
        }).then(res => {
          if (res.success) {
            res.data.map((item, index) => {
              item.number1 = index + 1;
            });
            this.dataList = res.data;
            console.log(this.dataList);
          } else {
            this.dataList = [];
          }
          if (this.tabName === '任务管理') {
            this.getFilePage();
          }
        });
      },
    async collectData() {
      const { getBodyByProduce, queryHeaderByMenuId } = this;
      const query = this.$route.query;
      console.log(query);
      let filterList = null;
      const filter = getPropertyOfQuery(query.filter);
      const bodyByProduceData = getPropertyOfQuery(query.data);

      if (filter) {
        filterList = [];
        for (const key in filter) {
          filterList.push({
            col: key,
            value: filter[key],
            symbol: 'eq'
          });
        }
      }

      const bodyByProduceRequestData = Object.assign({}, { filterList: filterList || undefined }, bodyByProduceData);

      await getBodyByProduce(bodyByProduceRequestData);
      if (query.menuId) {
        await queryHeaderByMenuId({ menuId: query.menuId, formGuid: '' });
      }
    }

  },

  render() {
    const rendermovableSwiper =this.$scopedSlots.default
    const renderFileNos = () => {
      return this.fileNos.map(fileNo => {
        return (
          <File-No-Item
            fileNo={fileNo}
            title={ fileNo.tableName }
            content={ fileNo.content }
            imgSrc={ fileNo.imgSrc || '' }
            linkPage={ fileNo.linkPage || '' }
          />
        );
      });
    };
    const renderempty = () => {
      return (<div style='text-align:center;color:gray;'>暂无数据</div>);
    };
    return (
      <div class='formViewPage'>

        <div class='formViewPage-head'>
          <Form-Head />
        </div>

        <div class='formViewPage-container'>
          {/* 详情 */}
          <div class='formViewPage-FormDetail' >
            <Form-Detail
              item={ this.produceData }
            />
          </div>

          <div class='formViewPage-body'>

         {
           this.levelNum==='1'?
           <div>
               <div style='padding: 0px 5px 13px 10px;'>
               {this.fileNos[0].tableName}
               </div>
               {
                 this.dataList.length !== 0
                   ?  <movableSwiper
                style='top: 0px;left: -13px;' dataList={this.dataList}  height={this.movHeight}
                scopedSlots={{
                          default: props => {
                            const  {movSlotData} = props
                           return (
                           <view onclick={
                             function (){
                               console.log(props.movSlotData)
                             }
                           }>
                             <view style=' text-align:center; height: 45px;line-height: 45px;display: flex;' >
                               <span style="flex:1;font-size:10px" >上一页</span>
                               <span style="flex:5;text-align:center">第{  movSlotData && movSlotData.number1 }/{ this.dataList.length }条</span>
                               <span style="flex:1;font-size:10px" >下一页</span>
                             </view>
                             {
                               this.header.map(o=>{
                                    return (
                                      <view style='display: flex;padding: 10px;border-bottom: 1px solid #d4d1d1;align-items: center;' >
                                        <view style='flex:1.4;font-size: 14px;' >{ o.title }:</view>
                                        <view style='flex:3;color: gray;font-size: 14px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;'>{movSlotData && movSlotData[o.dataIndex]}</view>
                                      </view>
                                    )
                               })
                             }
                             </view>
                           );
                         }
                       }} >
               </movableSwiper>
                   : renderempty()
               }

           </div>:
            <div>
            <h3 class='formViewPage-body-title'>
             一码通管贯穿始终
            </h3>
            {
              this.fileNos.length !== 0
                ? <div class='formViewPage-body-file-content'>{renderFileNos()}</div>
                : renderempty()
            }
            </div>
         }

          </div>
        </div>

      </div>
    );
  }
};
